<template>
  <div class="news-list">
    <van-pull-refresh
      v-model="isNewsLoading"
      success-text="刷新成功"
      @refresh="onNewsRefresh"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <NewsListItem
          v-for="(newsItem, index) in newsList"
          :key="index"
          :newsItem="newsItem"
        ></NewsListItem>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import NewsListItem from '@/components/NewsList-Iten.vue'
import { getChannelNewsListApi } from '@/api/home.js'
export default {
  name: 'NewsList',
  props: {
    channel: {
      type: Object,
      required: true
    }
  },
  components: {
    NewsListItem
  },
  data () {
    return {
      newsList: [],
      loading: false,
      finished: false,
      // 时间戳，更新下页的新闻
      timestamp: null,
      // 控制下拉刷新的显示关闭
      isNewsLoading: false
    }
  },
  created () {},
  methods: {
    // 新闻列表更新触发
    onLoad () {
      // 调用新闻请求
      getChannelNewsListApi({
        channel_id: this.channel.id,
        timestamp: this.timestamp || 1556789000001,
        with_top: 1
      }).then((res) => {
        // 赋值,拼接
        this.newsList.push(...res.data.data.results)
        // 加载状态结束
        this.loading = false

        // 判断results数组是否为空
        if (res.data.data.results.length) {
          // 不为空就更新时间戳
          this.timestamp = res.data.data.pre_timestamp
        } else {
          // 数据全部加载完成
          this.finished = true
        }
      })
    },
    // 下拉刷新触发
    onNewsRefresh () {
      // 调用更新新闻请求
      getChannelNewsListApi({
        channel_id: this.channel.id,
        timestamp: this.timestamp || 1556789000001,
        with_top: 1
      }).then((res) => {
        // 赋值，往上拼接
        this.newsList.unshift(...res.data.data.results)

        // 判断results数组是否为空
        if (res.data.data.results.length) {
          // 不为空就更新时间戳
          this.timestamp = res.data.data.pre_timestamp
        }
      })
      // 关闭下拉刷新
      this.isNewsLoading = false
    }
  }
}
</script>

<style lang="less" scoped>
.news-list {
  position: fixed;
  top: 90px;
  bottom: 50px;
  left: 0;
  right: 0;
  overflow-y: auto;
}
</style>
